package activator;

import library.service.Book;
import library.service.LibraryService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

public class LibraryConsumerServiceFactoryActivator implements BundleActivator {

	private ServiceReference serviceReference = null;
	private LibraryService libraryService = null;
	private final static String FILTER = "(factory=true)";

	public void start(BundleContext bundleContext) throws Exception {
		System.out.println("Bundle Consumer START");
		
		ServiceReference[] srvcRefArray = bundleContext
				.getAllServiceReferences(LibraryService.class.getName(), FILTER);
		if (srvcRefArray != null && srvcRefArray.length > 0) {
			serviceReference = srvcRefArray[0];
			libraryService = (LibraryService) bundleContext
					.getService(serviceReference);
			if (libraryService != null) {
				Book[] books = libraryService.listBooks();
				System.out.println("-----------------");
				for (int i = 0; i < books.length; i++) {
					System.out.println(books[i].toString());
				}
				System.out.println("-----------------");
			}
		}

	}

	public void stop(BundleContext bundleContext) throws Exception {
		System.out.println("Bundle Consumer STOP");
		
		if (serviceReference != null) {
			bundleContext.ungetService(serviceReference);
			serviceReference = null;
			libraryService = null;
		}
	}
}
